import React, { useState, useMemo, useCallback } from 'react';
import { View, Text, TouchableOpacity, Modal, StyleSheet, ScrollView, Dimensions, Image, ImageSourcePropType } from 'react-native';
import { AppStyles, AppColors, TextStyles } from '../theme/uiLib.config';
import { useRouter } from 'expo-router';
import Icon from 'react-native-vector-icons/Ionicons';
import { Colors } from 'react-native-ui-lib';

const { width: screenWidth, height: screenHeight } = Dimensions.get('window');

interface Task {
    name: string;
    points: number;
    status?: 'completed' | 'pending';
    image?: ImageSourcePropType;
}

interface MemberData {
    id: string;
    phone: string;
    tasks: Task[];
}

interface GetMorePointsModalProps {
    isVisible: boolean;
    onClose: () => void;
    customStyle?: any;
}

const GetMorePointsModal: React.FC<GetMorePointsModalProps> = ({ isVisible, onClose, customStyle }) => {
    const router = useRouter();
    const [selectedTab, setSelectedTab] = useState('138****8000');
    const [memberData, setMemberData] = useState<MemberData[]>(() => [
        {
            id: '1',
            phone: '138****8000',
            tasks: [
                { name: '注册民生银行信用卡', points: 5000, image: require('../../assets/images/task/creditcard.jpg') },
                { name: '少儿重疾保险计划', points: 3000, image: require('../../assets/images/task/kidInsurance.jpg') },
                { name: '邀请好友', points: 1000, image: require('../../assets/images/task/sign.jpg') },
            ],
        },
        {
            id: '2',
            phone: '139****9000',
            tasks: [
                { name: '少儿重疾保险计划', points: 3000, image: require('../../assets/images/task/kidInsurance.jpg') },
                { name: '邀请好友', points: 1000, image: require('../../assets/images/task/sign.jpg') },
            ],
        },
        {
            id: '3',
            phone: '133****7323',
            tasks: [
                { name: '每日签到', points: 120, status: 'completed', image: require('../../assets/images/task/sign.jpg') },
                { name: '少儿重疾保险计划', points: 3000, image: require('../../assets/images/task/kidInsurance.jpg') },
                { name: '邀请好友', points: 1000, image: require('../../assets/images/task/sign.jpg') },
            ],
        },
    ]);

    const currentMember = useMemo(() => memberData.find(member => member.phone === selectedTab), [selectedTab, memberData]);

    const handleTaskPress = useCallback((taskIndex: number) => {
        setMemberData(prevMemberData => {
            return prevMemberData.map(member => {
                if (member.phone === selectedTab) {
                    const updatedTasks = member.tasks.map((task, index) => {
                        if (index === taskIndex) {
                            return { ...task, status: 'completed' as 'completed' };
                        }
                        return task;
                    });
                    return { ...member, tasks: updatedTasks };
                }
                return member;
            });
        });
    }, [selectedTab, setMemberData]);

    return (
        <Modal
            transparent={true}
            animationType="fade"
            visible={isVisible}
        >
            <View style={styles.modalOverlay}>
                <View style={[styles.modalContent]}>
                    <View style={styles.header}>
                        <Text style={[TextStyles.h3, { flex: 1, textAlign: 'center' }]}>获取更多积分</Text>
                        <TouchableOpacity
                            onPress={onClose}
                            style={styles.closeButton}
                            hitSlop={{ top: 10, bottom: 10, left: 10, right: 10 }}
                        >
                            <Icon name="close-circle-outline" size={28} color={AppColors.grey20} />
                        </TouchableOpacity>
                    </View>
                    <View style={styles.divider} />
                    <Text style={styles.description}>为每位家庭成员精选以下快速获取积分的任务，完成即可获得相应积分奖励</Text>
                    <ScrollView style={styles.taskList}>
                    <View style={[{flex: 1, backgroundColor: 'transparent', marginBottom: 10}]}>
                        <ScrollView
                            horizontal
                            showsHorizontalScrollIndicator={false}
                        >
                        <View style={{ flexDirection: 'row', justifyContent: 'flex-start' }}>
                            {memberData.map((member) => (
                                <TouchableOpacity
                                    key={member.id}
                                    style={{
                                        marginRight: 10,
                                        paddingVertical: 10,
                                        paddingHorizontal: 16,
                                        backgroundColor: selectedTab === member.phone ? AppColors.grey10 : Colors.blueplus,
                                        borderRadius: 20,
                                        borderWidth: 1,
                                        borderColor: selectedTab === member.phone ? AppColors.grey20 : AppColors.blueplus,
                                    }}
                                    onPress={() => setSelectedTab(member.phone)}
                                >
                                    <Text style={[
                                        TextStyles.small,
                                        {
                                            color: selectedTab === member.phone ? Colors.blueplus : AppColors.white,
                                            fontWeight: selectedTab === member.phone ? 'bold' : 'normal'
                                        }
                                    ]}>
                                        {member.phone}
                                    </Text>
                                </TouchableOpacity>
                            ))}
                        </View>
                    </ScrollView>

                    </View>
                  
                        {currentMember?.tasks.map((task, index) => (
                            <TouchableOpacity
                                key={index}
                                style={styles.taskItemContainer}
                                activeOpacity={0.7}
                                onPress={() => handleTaskPress(index)}
                            >
                                <View style={styles.taskItem}>
                                    <View style={styles.taskInfo}>
                                        <Text style={styles.taskName}>{task.name}</Text>
                                        <Text style={styles.taskPoints}>+{task.points}</Text>
                                    </View>
                                    <Text style={[
                                        styles.taskStatus,
                                        task.status === 'completed' ? styles.taskCompleted : styles.taskPending
                                    ]}>
                                        {task.status === 'completed' ? '任务完成' : '去完成'}
                                    </Text>
                                </View>
                                {task.image && (
                                    <Image source={task.image} style={styles.taskImage} />
                                )}
                            </TouchableOpacity>
                        ))}
                    </ScrollView>
                    <TouchableOpacity
                        style={styles.confirmButton}
                        onPress={onClose}
                        activeOpacity={0.8}
                    >
                        <Text style={styles.confirmButtonText}>确定</Text>
                    </TouchableOpacity>
                </View>
            </View>
        </Modal>
    );
};

const styles = StyleSheet.create({
    modalOverlay: {
        flex: 1,
        backgroundColor: 'rgba(0, 0, 0, 0.7)',
        justifyContent: 'center',
        alignItems: 'center',
    },
    modalContent: {
        backgroundColor: 'white',
        padding: 12,
        borderRadius: 16,
        width: screenWidth * 0.95,
        height: screenHeight * 0.85,
    },
    header: {
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center',
        marginTop: 10,
        marginBottom: 20,
    },
    closeButton: {
        position: 'absolute',
        right: 0,
    },
    divider: {
        borderBottomWidth: 1,
        borderBottomColor: AppColors.grey10,
        width: '100%',
        marginBottom: 8,
    },
    description: {
        ...TextStyles.small,
        color: AppColors.secondary,
        marginBottom: 12,
        lineHeight: 20,
    },
    taskList: {
        flex: 1,
        marginTop: 6,
    },
    taskItemContainer: {
        marginBottom: 12,
        backgroundColor: AppColors.grey10,
        borderRadius: 12,
        overflow: 'hidden',
    },
    taskItem: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
        padding: 16,

    },
    taskInfo: {
        flexDirection: 'row',
        alignItems: 'center',
        flex: 1,
    },
    taskName: {
        ...TextStyles.primary,
        marginRight: 8,
    },
    taskPoints: {
        ...TextStyles.number,
        color: AppColors.golden,
    },
    taskStatus: {
        ...TextStyles.small,
        paddingHorizontal: 12,
        paddingVertical: 6,
        borderRadius: 12,
    },
    taskCompleted: {
        color: AppColors.success,
        backgroundColor: `${AppColors.success}20`,
    },
    taskPending: {
        color: AppColors.primary,
        backgroundColor: `${AppColors.primary}10`,
    },
    taskImage: {
        width: '100%',
        height: 120,
        resizeMode: 'cover',
    },
    confirmButton: {
        width: '100%',
        height: 44,
        borderRadius: 22,
        backgroundColor: AppColors.primary,
        alignItems: 'center',
        justifyContent: 'center',
        marginTop: 20,
    },
    confirmButtonText: {
        ...TextStyles.small,
        color: AppColors.white,
    },
});

export default GetMorePointsModal; 